package a10_动态规划;

/**
 * <p>
 * a44_最长公共子序列
 * </p>
 *
 * @author flyduck
 * @since 2025/2/26
 */
public class a44_最长公共子序列 {
    //abcde
    //ace

    //dp[i][j]:包含chars1[i-1]和包含chars2[j-1]的最长公共子序列(不是以这个结尾)

    // if(chars1[i-1] == chars2[j-1]){
    //     dp[i][j] = dp[i-1][j-1] + 1;
    // }else{
    //     dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
    // }

    //思考问题：为啥chars1[i-1] != chars2[j-1]，只有这两种情况dp[i][j-1],dp[i-1][j]
    //一种情况：chars1[i-1]和chars2的0~j-2有可能相等
    //一种情况：chars2[i]和chars1的0~i-2有可能相等

    //初始化
    //dp[i][0]=0
    //dp[0][j]=0
    public int longestCommonSubsequence(String text1, String text2) {
        char[] chars1 = text1.toCharArray();
        char[] chars2 = text2.toCharArray();

        int[][] dp = new int[chars1.length+1][chars2.length+1];

        for (int i = 1; i <= chars1.length; i++) {
            for (int j = 1; j <= chars2.length; j++) {
                if(chars1[i-1] == chars2[j-1]){
                    dp[i][j] = dp[i-1][j-1] + 1;
                }else {
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }

        return dp[chars1.length][chars2.length];
    }
}
